package com.antdesignbackend.backend.controller;

import com.antdesignbackend.backend.accountmanage.entity.entityVo.UserMenuVo;
import com.antdesignbackend.backend.accountmanage.service.UserMenuService;
import com.antdesignbackend.backend.city.entity.City;
import com.antdesignbackend.backend.city.service.CityService;
import com.antdesignbackend.backend.common.Des3Util;
import com.antdesignbackend.backend.common.GoogleAuthenticator;
import com.antdesignbackend.backend.common.returnResult.ReturnCode;
import com.antdesignbackend.backend.common.returnResult.ReturnVO;
import com.antdesignbackend.backend.config.WebConfig;
import com.antdesignbackend.backend.district.entity.District;
import com.antdesignbackend.backend.district.service.DistrictService;
import com.antdesignbackend.backend.entity.Enterprise;
import com.antdesignbackend.backend.entity.Roles;
import com.antdesignbackend.backend.entity.Users;
import com.antdesignbackend.backend.entity.entityVo.RoleMenuVo;
import com.antdesignbackend.backend.entity.entityVo.UserRoleVo;
import com.antdesignbackend.backend.service.*;
import com.antdesignbackend.backend.town.entity.Town;
import com.antdesignbackend.backend.town.service.TownService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;


@Controller
public class LoginController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    UserService userService;
    @Autowired
    UserRolesService userRolesService;
    @Autowired
    ILogService logService;
    @Autowired
    EnterpriseService enterpriseService;
    @Autowired
    RolesService rolesService;
    @Autowired
    RoleMenuService roleMenuService;
    @Autowired
    UserMenuService userMenuService;
    @Autowired
    CityService cityService;
    @Autowired
    DistrictService districtService;
    @Autowired
    TownService townService;

    /**
     * 跳转登录页
     *
     * @return
     */
    @GetMapping(value = "/login")
    public String login() {
        return "login";
    }

    @GetMapping(value = "/error404")
    public String error404() {
        return "404";
    }

    @GetMapping(value = "/error")
    public String error() {
        return "404";
    }

    @GetMapping(value = "/error500")
    public String error500() {
        return "500";
    }

    /**
     * 验证登录请求
     *
     * @param loginName
     * @param password
     * @param request
     * @return
     */
    @PostMapping(value = "/checkLogin")
    @ResponseBody
    public ReturnVO checkLogin(String loginName, String password, HttpServletRequest request) throws Exception {

        try {
//            password = Des3Util.decode(password);
            //验证用户名密码是否正确
            QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("UserName", loginName).
                    eq("Password", DigestUtils.md5DigestAsHex(password.getBytes())).
                    eq("activity", 1);
            Users users = userService.getOne(queryWrapper);

            if (users != null) {

                //判断用户是否是企业用户
                Enterprise enterprise = new Enterprise();
                if (users.getEid() != null && users.getEid() != 0){ //是企业用户
                    //根据企业id找到企业
                    enterprise = enterpriseService.getById(users.getEid());
                    if (enterprise != null){
                        if (enterprise.getExamine() != 1 || enterprise.getActivity() != 1){
                            return new ReturnVO(ReturnCode.VerificationFailed, "登录失败");
                        }
                    }else {
                        return new ReturnVO(ReturnCode.VerificationFailed, "登录失败");
                    }
                }

                //查询角色信息
                List<UserRoleVo> userRoleVos = userRolesService.selectUserRoleList(
                        new QueryWrapper<UserRoleVo>().eq("UserName", loginName).
                                eq("Password", DigestUtils.md5DigestAsHex(password.getBytes())), null);
                //获取角色ID
                StringBuilder roles = new StringBuilder();
                StringBuilder roleCheckKeys = new StringBuilder();
                for (UserRoleVo userRoleVo : userRoleVos) {
                    roles.append(userRoleVo.getRoleID()).append(",");
                    //记录roles表checkName，用来注解判断角色是否允许
                    roleCheckKeys.append(userRoleVo.getRoleCheckName()).append(",");
                }

                roles = new StringBuilder(roles.substring(0, roles.length() - 1));
                roleCheckKeys = new StringBuilder(roleCheckKeys.substring(0, roleCheckKeys.length() - 1));

                HttpSession session = request.getSession();
                //判断用户名密码是否正确,用户名当作key
                session.setAttribute("LoginName", loginName);
                session.setAttribute("RoleID", roles.toString());
                session.setAttribute("RoleCheckKey", roleCheckKeys.toString());
                session.setAttribute("Key", users.getKeyName());
                session.setAttribute("RoleName", userRoleVos.get(0).getRoleName());
                session.setAttribute("UserType", userRoleVos.get(0).getUserType());
                session.setAttribute("UserID", userRoleVos.get(0).getUserID());
                session.setAttribute("EnterpriseID",enterprise.getEnterpriseId());
                session.setAttribute("EnterpriseName",enterprise.getEnterpriseName());
                session.setAttribute("EnterpriseTypes",enterprise.getTypes());
                session.setAttribute("Animal",enterprise.getAnimal());
                session.setAttribute("AnimalTypes",enterprise.getAnimalTypes());
                session.setAttribute("Grade",users.getGrade());
                session.setAttribute("IsEnterprise",users.getEid() != null ? 1 : 0);
                session.setAttribute("authType",users.getAuthType());
                session.setAttribute("day1",enterprise.getDay1());
                session.setAttribute("day2",enterprise.getDay2());
                session.setAttribute("birthDay",enterprise.getBirthDay());
                session.setAttribute("harmlessId",enterprise.getHarmlessId());
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                logger.info(loginName + ":登录成功，登录时间" + df.format(new Date()));
                logService.WriteLog(1, "系统登录成功", loginName);
                //组装返回js数据
                ReturnVO returnVO = new ReturnVO();
                returnVO.setCode("200");
                Map<String, Object> map = new HashMap<>();
                map.put("LoginName", loginName);
                map.put("RoleID", roles.toString());
                if (users.getEid() != null && users.getEid() != 0){
                    map.put("RoleName", enterprise.getEnterpriseName());
                }else {
                    //显示对应角色的信息
                    Roles roles1 = rolesService.getById(users.getUserType());
                    if (roles1 != null){
                        map.put("RoleName", roles1.getRoleName());
                    }
                }

                /**
                 * 菜单
                 */
                if (users.getGrade() == null || users.getGrade() == 1){ //一级账户，主账号
                    QueryWrapper<RoleMenuVo> wrapper = new QueryWrapper<>();
                    wrapper.eq("rm.RoleID", roles.toString()).eq("activity", 1);
                    List<RoleMenuVo> roleMenuVos = roleMenuService.selectRoleMenuList(wrapper, null);

                    if (roleMenuVos.size() > 0) {
                        if ("3".equals(users.getUserType())){
                            //如果是猪1，移除产蛋记录，如果是鸡0，移除繁殖记录
                            Iterator iterator = roleMenuVos.iterator();
                            while (iterator.hasNext()){
                                // 获得所有菜单
                                RoleMenuVo roleMenuVo1 = (RoleMenuVo)iterator.next();
                                if (enterprise.getAnimalTypes() != null){
                                    if (enterprise.getAnimalTypes() == 1){ //猪，牛，羊
                                        if ("egg".equals(roleMenuVo1.getKeyName())){ //移除产蛋记录
                                            iterator.remove();
                                        }
                                    }
                                    if (enterprise.getAnimalTypes() == 0){ //养鸡，鸭...
                                        if ("reproductionManage".equals(roleMenuVo1.getKeyName())){ //移除繁殖记录
                                            iterator.remove();
                                        }
                                        if ("monthReportRecord".equals(roleMenuVo1.getKeyName())){ //移除月报管理
                                            iterator.remove();
                                        }
                                        if ("ReservationManage".equals(roleMenuVo1.getKeyName())){ //移除留种记录
                                            iterator.remove();
                                        }
                                        if ("BasicManagement".equals(roleMenuVo1.getKeyName())){ //移除基础设置
                                            iterator.remove();
                                        }
                                        if ("SetDay".equals(roleMenuVo1.getKeyName())){ //移除自动转型天数设置
                                            iterator.remove();
                                        }
                                        if ("SetBirthDay".equals(roleMenuVo1.getKeyName())){ //移除预产期天数设置
                                            iterator.remove();
                                        }
                                    }
                                }
                            }
                        }
                        returnVO.setCode("200");
                        List<LinkedHashMap<String,Object>> linkedHashMaps=new ArrayList<>();
                        for(RoleMenuVo roleMenuVo:roleMenuVos){
                            LinkedHashMap<String,Object> stringObjectLinkedHashMap=new LinkedHashMap<>();
                            stringObjectLinkedHashMap.put("menuId",roleMenuVo.getId());
                            stringObjectLinkedHashMap.put("textCH",roleMenuVo.getTextCH());
                            linkedHashMaps.add(stringObjectLinkedHashMap);
                        }
                        map.put("Menus", linkedHashMaps);
                    } else
                        returnVO.setCode("503");
                }else if (users.getGrade() == 2){ //二级账户，子账号
                    //根据用户id查询到对应的菜单
                    QueryWrapper<UserMenuVo> wrapper = new QueryWrapper<>();
                    wrapper.eq("um.UserId",users.getUserID());
                    List<UserMenuVo> list = userMenuService.selectUserMenuList(wrapper);
                    List<LinkedHashMap<String,Object>> linkedHashMaps=new ArrayList<>();
                    for(UserMenuVo userMenuVo:list){
                        LinkedHashMap<String,Object> stringObjectLinkedHashMap=new LinkedHashMap<>();
                        stringObjectLinkedHashMap.put("menuId",userMenuVo.getId());
                        stringObjectLinkedHashMap.put("textCH",userMenuVo.getTextCH());
                        linkedHashMaps.add(stringObjectLinkedHashMap);
                    }
                    map.put("Menus", linkedHashMaps);
                }
                String AuthCityName = "";
                String AuthDistrictName = "";
                String AuthTownName = "";
                City city = cityService.getById(users.getAuthCity());
                District district = districtService.getById(users.getAuthDistrict());
                Town town = townService.getById(users.getAuthTown());
                if (city != null){
                    AuthCityName = city.getCity_name();
                }
                if (district != null){
                    AuthDistrictName = district.getDistrict_name();
                }
                if (town != null){
                    AuthTownName = town.getTown__name();
                }
                map.put("UserType", String.valueOf(userRoleVos.get(0).getUserType()));
                map.put("UserID", String.valueOf(userRoleVos.get(0).getUserID()));
                map.put("AuthCity", users.getAuthCity());
                map.put("AuthDistrict", users.getAuthDistrict());
                map.put("AuthTown", users.getAuthTown());
                map.put("AuthType", users.getAuthType());
                map.put("userName", enterprise.getUserName());
                map.put("phone", enterprise.getPhone());
                map.put("animal", enterprise.getAnimal());
                map.put("AnimalTypes", enterprise.getAnimalTypes());
                map.put("AuthCityName", AuthCityName);
                map.put("AuthDistrictName", AuthDistrictName);
                map.put("AuthTownName", AuthTownName);
                returnVO.setData(map);
                return returnVO;

            } else {
                return new ReturnVO(ReturnCode.VerificationFailed, "登录失败");

            }
        }
        catch(Exception ex)
        {
            System.out.println(ex.getMessage());
            return new ReturnVO(ReturnCode.VerificationFailed, "登录失败");
        }
    }


    public static void main(String[] arg) {
        //比如对密码进行 md5 加密
        //1、加密之后你也不知道原始密码是什么的，只能通过密文比对的。认可这种方式用DigestUtils下面的加密方法，这个是spring 自带的
        //前端段加密解密的使用。后台使用Des3Util；前端js使用C_Des3
        String md5Pass = DigestUtils.md5DigestAsHex("123456_123456".getBytes());
        System.out.println(md5Pass);
    }
}
